package com.zengchen.gateway.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.gateway.webflux.ProxyExchange;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class ContentCenterController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    private final String checkParam = "chid";
    private final String checkParamValue = "wx";

//    @GetMapping("/content-center/poem/list")
//    public Object poemList(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        // 判断chid=wx
//        String value = Optional.ofNullable(request.getParameter(checkParam)).orElse("");
//        if (!checkParamValue.equalsIgnoreCase(value)) {
//            response.setStatus(HttpStatus.NOT_FOUND.value());
//            return response;
//        }
//        // 用ribbon选出1个可用的实例，
//        ServiceInstance serviceInstance = loadBalancerClient.choose("content-center");
//        String uri = serviceInstance.getUri() + "/poem/list";
//        return response.sendRedirect(uri);
//    }

    @GetMapping("/content-center/poem/list")
    public Mono<ResponseEntity<String>> proxy(ProxyExchange<String> proxy, @PathVariable String ids) throws Exception {
        // 判断chid=wx
//        String value = request.queryParam(checkParam).orElse("");
//        if(!checkParamValue.equalsIgnoreCase(value)){
//            return null;
//        }
        // 用ribbon选出1个可用的实例，
        ServiceInstance serviceInstance = loadBalancerClient.choose("content-center");
        String uri = serviceInstance.getUri() + "/poem/list";
        return proxy.uri(uri).get();
    }
}
